//
//  MainWindowController.m
//  test-TextView
//
//  Created by 杨岑 on 2/3/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#import "TestTextViewWC.h"
#import "NSMutableAttributedString+Ext.h"
#import "MyTextView.h"
#import "TextTableBuilder.h"


@interface TestTextViewWC ()
@property (unsafe_unretained) IBOutlet MyTextView* textView;
@property (weak) IBOutlet NSTextField *multiLineLabel;
@property (weak) IBOutlet NSView* textViewContainer;
@property (weak) IBOutlet NSLayoutConstraint *textViewHeightConstraint;
@end


@implementation TestTextViewWC
{
    CGFloat _gap;
}

- (void)awakeFromNib
{
    _textView.continuousSpellCheckingEnabled = NO;
    _textView.grammarCheckingEnabled = NO;
    _textView.textContainerInset = NSMakeSize(20, 30);
    
    [NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(timer_tick:) userInfo:nil repeats:YES];
    
    //_gap = _textView.enclosingScrollView.frame.size.height - _textView.frame.size.height;
    
    _textView.onFrameChange = ^(NSRect frame) {
        NSLog(@"%@: frameChange: %.1f", self, frame.size.height);
        //_textViewHeightConstraint.constant = frame.size.height + _gap;
        //NSLog(@"constraint.constant: %.3f", _textViewHeightConstraint.constant);
        //[self.window visualizeConstraints:@[_textViewHeightConstraint]];
    };
}

- (void)timer_tick:(NSTimer*)timer
{
    static CGFloat lastGap = 0;
    
    if (_textView.enclosingScrollView.verticalScroller.hidden)
    {
        lastGap = _gap;
    }
    else
    {
        if (lastGap < _gap) lastGap = _gap;
        else
        {
            lastGap++;
        }
        NSLog(@"lastGap: %.1f", lastGap);
        _textViewHeightConstraint.constant = _textView.bounds.size.height + lastGap;
    }
}

- (IBAction)test_click:(id)sender {
    NSURL* url = [NSURL URLWithString:@"http://www.apple.com"];
    NSMutableAttributedString* as = [[NSMutableAttributedString alloc] initWithString:@"Hyperlink test\n"];
    NSMutableAttributedString* linkAttrString = [NSMutableAttributedString hyperlinkFromString:@"apple.com" withURL:url];
    //NSDictionary* linkAttr = @{NSForegroundColorAttributeName: [NSColor cyanColor], NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
    //[linkAttrString addAttributes:linkAttr range:NSMakeRange(0, linkAttrString.length)];
    [as appendAttributedString:linkAttrString];
    _multiLineLabel.attributedStringValue = as;
}

- (IBAction)test2_click:(id)sender {
    NSMutableDictionary* linkAttr = [NSMutableDictionary dictionaryWithDictionary:_textView.linkTextAttributes];
    linkAttr[NSForegroundColorAttributeName] = [NSColor cyanColor];
    _textView.linkTextAttributes = linkAttr;
    
    // create the attributed string
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];
    
    // create the url and use it for our attributed string
    NSURL* url = [NSURL URLWithString: @"http://www.apple.com"];
    
    [string appendAttributedString:[NSMutableAttributedString attachmentFromImage:[NSImage imageNamed:NSImageNameComputer]]];

    [string appendAttributedString:[[NSAttributedString alloc] initWithString:@"好雨知时节，当春乃发生\n" attributes:@{NSForegroundColorAttributeName: [NSColor purpleColor], NSFontAttributeName: [NSFont userFontOfSize:32]}]];
    NSMutableAttributedString* linkString = [NSMutableAttributedString hyperlinkFromString:@"随风潜入夜，润物细无声\n\n" withURL:url];
    NSRange all = NSMakeRange(0, linkString.length);
    [linkString addAttribute:NSFontAttributeName value:[NSFont userFontOfSize:25] range:all];
    [string appendAttributedString:linkString];
    
    NSMutableAttributedString* linksAttrString = [[NSMutableAttributedString alloc] init];
    // apply it to the NSTextView's text storage
    int n = rand() % 5 + 1;
    for (int i = 0; i < n; i++)
    {
        [linksAttrString appendAttributedString:string];
    }
    
    [[_textView textStorage] setAttributedString:[[NSAttributedString alloc] initWithString:@"" attributes:nil]];
    _textViewHeightConstraint.constant = 0;
    [[_textView textStorage] setAttributedString:linksAttrString];
    
    NSSize newSize = [_textView computedContentSize:_textView.bounds.size.width];
    NSLog(@"computedContentSize: %.1f,%1.f", newSize.width, newSize.height);
}

- (IBAction)test3_click:(id)sender
{
    _textViewHeightConstraint.constant = 0;
    
    TextTableBuilder* t = [TextTableBuilder createWithTitle:@"icon" logTitle:@"text"];
    [self.textView.textStorage setAttributedString:t.headerRowAttrString];
    int n = rand() % 5 + 1;
    for (int i = 0; i < n; i++)
    {
        NSString* s = [NSString stringWithFormat:@"text #%d\ntext\ntext", i];
        NSMutableAttributedString* rowString = [t addRow:@"" logText:s textColor:[NSColor blueColor]];
        [self.textView.textStorage appendAttributedString:rowString];
    }
}

- (IBAction)test4_click:(id)sender {
    NSMutableDictionary* a = [NSMutableDictionary dictionaryWithDictionary:self.textView.linkTextAttributes];
    a[NSForegroundColorAttributeName] = [NSColor blueColor];
    self.textView.linkTextAttributes = a;
}

- (NSMenu *)textView:(NSTextView *)view
                menu:(NSMenu *)menu
            forEvent:(NSEvent *)event
             atIndex:(NSUInteger)charIndex
{
    //return nil;
    return menu;
}

- (BOOL)textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
{
    NSLog(@"Command selector: %@", NSStringFromSelector(commandSelector));
    NSEvent* event = [[NSApplication sharedApplication] currentEvent];
    
    if (event.modifierFlags & NSEventModifierFlagCommand)
    {
        if ([event.charactersIgnoringModifiers isEqualToString:@"a"])
        {
            [self.textView selectAll:self];
            return YES;
        }
    }
    return NO;
}

- (BOOL)textView:(NSTextView *)textView clickedOnLink:(id)link atIndex:(NSUInteger)charIndex
{
    NSLog(@"Link clicked: %@ @ %lu %.1f", link, charIndex, textView.bounds.size.height);
    return YES;
}

- (void)textDidChange:(NSNotification *)notification
{
    //NSLog(@"textDidChange: %.1f", _textView.bounds.size.height);
}


@end
